// Copyright 2022 Hollson. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package main

import (
	"errors"
	"fmt"
)

const stackSize int = 22                //栈的容量

type TreeNode struct {
	Left *TreeNode
	Value int
	Right *TreeNode
}

type Stack struct {                     //栈结构
	Size int
	Values []*TreeNode
}

func CreateStack() Stack{                //创建栈
	s := Stack{}
	s.Size = stackSize
	return s
}

func (s *Stack) IsFull() bool {          //栈满
	return len(s.Values) == s.Size
}

func (s *Stack) IsEmpty() bool {          //栈空
	return len(s.Values) == 0
}

func (s *Stack) Push(a *TreeNode) error {       //入栈
	if s.IsFull() {
		return errors.New("Stack is full,push failed")
	}
	s.Values = append(s.Values,a)
	return nil
}

func (s *Stack) Pop() (*TreeNode,error) {//出栈,并返回其值
	if s.IsEmpty() {
		return nil ,errors.New("Out of index,len(stack) is 0")
	}
	res := s.Values[len(s.Values)-1]
	s.Values = s.Values[:len(s.Values)-1]
	return res,nil
}

func (s *Stack) Peek() (*TreeNode,error) {//查看栈顶元素
	if s.IsEmpty() {
		return nil ,errors.New("Out of index,len(stack) is 0")
	}
	return s.Values[len(s.Values)-1],nil
}

func (s *Stack) Traverse() {
	if s.IsEmpty() {
		fmt.Println("Stack is empty")
	}else {
		fmt.Println(s.Values)
	}
}